
import HttpMethod from './../../common/HttpMethod';
import UrlConst from './UrlConst';
import DomHelper from './../../common/DomHelper';
import OkexWebUtils from './OkexWebUtils';

const OkexSpotWebUtils = OkexWebUtils.okexSpotWebUtils();

export default class SpotTradeHelper {

    constructor({
        diffPrice = 0.0001,
    }) {
        this.config = {
            isFirstLoad: true,//首次加载
            diffPrice: Number(diffPrice),
            okexSpotAsks: new Map(),
            okexSpotBids: new Map(),
            okexSpotAskPrices: [],
            okexSpotBidPrices: [],
        };
    }

    calcDepth(res) {
        const self = this;
        if (self.config.isFirstLoad) {
            //sell
            const sellListLi = document.querySelectorAll('.sell-list li');
            for (let i = 0, len = sellListLi.length; i < len; i++) {
                const sellLi = sellListLi[i];
                const sellPrice = Number(sellLi.children[0].innerHTML.replace(/,/, ''));
                const sellTotalSize = Number(sellLi.children[1].innerHTML.replace(/,/, ''));
                if (sellTotalSize > 0) {
                    self.config.okexSpotAsks.set(sellPrice, sellTotalSize);
                }
            }
            self.config.okexSpotAskPrices = Array.from(self.config.okexSpotAsks.keys()).sort();
            //buy
            const buyListLi = document.querySelectorAll('.buy-list li');
            for (let i = 0, len = buyListLi.length; i < len; i++) {
                const buyLi = buyListLi[i];
                const buyPrice = Number(buyLi.children[0].innerHTML.replace(/,/, ''));
                const buyTotalSize = Number(buyLi.children[1].innerHTML.replace(/,/, ''));
                if (buyTotalSize > 0) {
                    self.config.okexSpotBids.set(buyPrice, buyTotalSize);
                }
            }
            self.config.okexSpotBidPrices = Array.from(self.config.okexSpotBids.keys()).sort();
        }
        const data = res.data;
        //异步处理买入数据
        OkexSpotWebUtils.taskRun(() => {
            if (data.asks && data.asks.length > 0) {
                for (let i = 0, len = data.asks.length; i < len; i++) {
                    const ask = data.asks[i];
                    const price = Number(ask.price);
                    const totalSize = Number(ask.totalSize);
                    if (totalSize === 0) {
                        self.config.okexSpotAsks.delete(price);
                    } else {
                        self.config.okexSpotAsks.set(price, totalSize);
                    }

                    self.config.okexSpotAskPrices = Array.from(self.config.okexSpotAsks.keys()).sort();
                    const thatDiffPrice = (self.config.okexSpotAskPrices[0] * 10000 - self.config.okexSpotBidPrices[self.config.okexSpotBidPrices.length - 1] * 10000) / 10000;
                    if (thatDiffPrice >= self.config.diffPrice) {
                        const thatBidPrice = self.config.okexSpotBidPrices[self.config.okexSpotBidPrices.length - 1];
                        const thatBidSize = self.config.okexSpotBids.get(thatBidPrice);
                        const thatAskPrice = self.config.okexSpotAskPrices[0];
                        const thatAskSize = self.config.okexSpotAsks.get(thatAskPrice);
                        OkexSpotWebUtils.log(`买入价:${thatBidPrice},数量:${thatBidSize},卖出价：${thatAskPrice},数量:${thatAskSize},差价：${thatDiffPrice}`, 1);
                        OkexSpotWebUtils.log(self.config.okexSpotAskPrices, 1);
                        OkexSpotWebUtils.log(self.config.okexSpotBidPrices, 1);
                    }
                }
            }
        });

        //异步处理卖出数据
        OkexSpotWebUtils.taskRun(() => {
            if (data.bids && data.bids.length > 0) {
                for (let i = 0, len = data.bids.length; i < len; i++) {
                    const bid = data.bids[i];
                    const price = Number(bid.price);
                    const totalSize = Number(bid.totalSize);
                    if (totalSize === 0) {
                        self.config.okexSpotBids.delete(price);
                    } else {
                        self.config.okexSpotBids.set(price, totalSize);
                    }
                    self.config.okexSpotBidPrices = Array.from(self.config.okexSpotBids.keys()).sort();
                    const thatDiffPrice = (self.config.okexSpotAskPrices[0] * 10000 - self.config.okexSpotBidPrices[self.config.okexSpotBidPrices.length - 1] * 10000) / 10000;
                    if (thatDiffPrice >= self.config.diffPrice) {
                        const thatBidPrice = self.config.okexSpotBidPrices[self.config.okexSpotBidPrices.length - 1];
                        const thatBidSize = self.config.okexSpotBids.get(thatBidPrice);
                        const thatAskPrice = self.config.okexSpotAskPrices[0];
                        const thatAskSize = self.config.okexSpotAsks.get(thatAskPrice);
                        console.log(`买入价:${thatBidPrice},数量:${thatBidSize},卖出价：${thatAskPrice},数量:${thatAskSize},差价：${thatDiffPrice}`);
                        console.log(self.config.okexSpotAskPrices);
                        console.log(self.config.okexSpotBidPrices);
                    }
                }
            }
        });
    }

    /**
     * 发送请求
     * @param {string} url url
     * @param {any} data 数据
     * @param {string} method httpmethod
     */
    send(url, data, method = HttpMethod.post) {
        return fetch(url, {
            method: method,
            body: data ? JSON.stringify(data) : '{}',
            headers: {
                "Authorization": localStorage.getItem("token") || "",
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            credentials: 'include'
        }).then(res => res.json());
    }

    /**
     * 
     * @param {string} symbol chat-usdt
     * @param {number} strategyType 1-限价单 2-市价单 3-计划委托
     * @param {number} price 买入/卖出 价格
     * @param {number} side buy-1 sell-2
     * @param {number} size 买入/卖出 数量
     * @param {number} systemType 
     */
    addOrder(symbol, orderType, price, side, size, systemType) {
        const self = this;
        const url = UrlConst.spot.POST_SUBMIT_ORDER.replace('{0}', symbol);
        return self.send(url, {
            side: E,
            price: price.toFixed(4),
            size: size,
            systemType: OK_GLOBAL.productConfig.isMarginOpen && false ? 2 : 1,
            quoteSize: (price * size).toFixed(4),
            orderType: 1 == strategyType ? 0 : 1
        }, HttpMethod.post);
    }

    cancelOrder() {
        const self = this;
        const url = UrlConst.spot.POST_CANCEL_ORDER.replace('{0}', '').replace('{1}', '');
        return self.send(url, {}, HttpMethod.delete);
    }
}
